from flask import request

from flaskapp.entity.Message import Message
from flaskapp.util.Redprint import Redprint
from flaskapp.util.Result import Result
from datetime import datetime

api = Redprint('messages')
"""
    数据库中message表中to字段是消息对应给某个用户的userid
    to为0代表这条消息是公告，所有用户都可以查收
"""


# 获取所有公告
@api.route('/get_all_announcements', methods=['GET'])
def get_all_announcements():
    announcements = Message.query.filter_by(to='0').all()
    announcements_list = []
    for announcement in announcements:
        announcements_list.append(announcement.to_dict())
    return Result.success(announcements_list)


# 获取最新一条公告
@api.route('/get_latest_announcement', methods=['GET'])
def get_latest_announcement():
    current_time = datetime.now()
    announcement = Message.query.filter(Message.date <= current_time).order_by(Message.date.desc()).limit(1).first()
    if announcement is None:
        return Result.error(404, 'No announcement')
    else:
        return Result.success(announcement.to_dict())


# 获取某用户的私信
@api.route('/get_messages/<userid>', methods=['GET'])
def get_messages(userid):
    messages = Message.query.filter_by(to=userid).all()
    announcements = Message.query.filter_by(to='0').all()
    messages_list = []
    for announcement in announcements:
        messages_list.append(announcement.to_dict())
    for message in messages:
        messages_list.append(message.to_dict())
    return Result.success(messages_list)


# 管理员发送消息
@api.route('/send_message', methods=['POST'])
def send_messages():
    data = request.get_json()
    to = data['to']
    # to为0的时候则为公告
    msg = data['msg']
    date = datetime.now()
    new_msg = Message(to, msg, date)
    return Result.success(new_msg.to_dict(), 'send successfully')
